// 岗位管理页面 JS
Page({
  data: {
    jobs: [],
    publisherId: '',
    showRecommendModal: false,
    students: [],
    selectedStudents: [],
    currentJobId: null,
  },

  onLoad: function () {
    const publisher_id = wx.getStorageSync('username');
    if (publisher_id) {
      this.setData({
        publisher_id: publisher_id
      });
    }
    this.loadJobs();
    this.loadStudents();
  },

  //获取所有岗位信息
  loadJobs() {
    wx.showLoading({ title: '加载中' });
    wx.request({
      url: 'http://192.168.172.134:5000/api/getPositionWx',
      method: 'GET',
      success: (res) => {
        
        if (res.data.code === 200) {
          this.setData({ jobs: res.data.data });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  //获取所有学生信息
  loadStudents() {
    wx.request({
      url: 'http://192.168.172.134:5000/api/getAllStudents',
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({ students: res.data.data });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  //一键推荐
  recommendJob(e) {
    const JobId = e.currentTarget.dataset.id;
    this.setData({
      currentJobId: JobId,
      showRecommendModal: true,
      selectedStudents: [],
    });
  },

  // 选择学生
  handleSelectStudents(e) {
    const selectedStudents = e.detail.value
    this.setData({
      selectedStudents: selectedStudents
    })
  },

  // 关闭弹窗
  closeModal() {
    this.setData({ showRecommendModal: false });
  },

  // 确认推荐
  confirmRecommend() {
    const { currentJobId, selectedStudents, publisher_id } = this.data;
    console.log(this.data.selectedStudents);


    if (selectedStudents.length === 0) {
      wx.showToast({ title: '请选择学生', icon: 'none' });
      return;
    }

    wx.request({
      url: 'http://192.168.172.134:5000/api/recommendPosition',
      method: 'GET',
      data: {
        positionId: currentJobId,
        students: selectedStudents,
        publisherId: publisher_id
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '推荐成功' });
          this.closeModal();
        }
      }
    });
  },


  createJob() {
    wx.navigateTo({ url: '/pages/position_editor/position_editor' });
  },

  editJob(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/position_editor/position_editor?id=${id}` });
  },

  deleteJob(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该岗位吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: `http://192.168.172.134:5000/api/deletePosition/${id}`,
            method: 'GET',
            data: { id },
            success: (res) => {
              if (res.data.code === 200) {
                this.loadJobs();
                wx.showToast({ title: '删除成功' });
              }
            }
          });
        }
      }
    });
  },

});